#include "GraceCpp.h"
#include "GraceCppAPI.h"

namespace grace_cpp
{
	namespace file
	{

		CustomIniFile::CustomIniFile()
		{
		}

		CustomIniFile::~CustomIniFile()
		{
		}

		SimpleIniFile::SimpleIniFile(const TCHAR *FileName):CustomIniFile()
		{
			_tcscpy_s(m_FileName, MAX_PATH, FileName);
		}

		SimpleIniFile::~SimpleIniFile()
		{
			CustomIniFile::~CustomIniFile();
		}

		bool SimpleIniFile::SectionExists(const TCHAR* section)
		{
			if (!section)
				return false;

			size_t len = _tcslen(section);

			if (len == 0)
				return false;

			TCHAR namelist[4096];

			size_t total = ::GetPrivateProfileSectionNames(
				namelist, 
				sizeof(namelist)/sizeof(namelist[0]), 
				m_FileName);

			if (total == 0)
				return false;	

			bool flag = true;
			size_t j = 0;

			for(size_t i = 0; i < total; ++i)
			{
				TCHAR c1, c2;

				if (section[j] >= _T('a') && section[j] <= _T('z'))
					c1 = section[j] & ~32;
				else
					c1 = section[j];

				if (namelist[i] >= _T('a') && namelist[i] <= _T('z'))
					c2 = namelist[i] & ~32;
				else
					c2 = namelist[i];

				if (flag)
				{
					if (c1 == c2)
					{
						if (j == len)
							return true;
						else j++;
					}
					else if (0 == c2)
					{
						flag = true;
						j = 0;
					}
					else
						flag = false;
				}
				else if (0 == c2)
				{
					flag = true;
					j = 0;
				}	
			}

			return false;
		}

		bool SimpleIniFile::KeyExists(
			const TCHAR* SectionName,
			const TCHAR* KeyName)
		{
			return true;
		}

		int SimpleIniFile::ReadInteger(
			const TCHAR* section,
			const TCHAR* key,
			int _default) 
		{
			return ::GetPrivateProfileInt(section, key, _default, m_FileName);
		}

		TCHAR* SimpleIniFile::ReadString(
			const TCHAR* section,
			const TCHAR* key,
			const TCHAR* _default,
			TCHAR *buf,
			size_t len)
		{
			if (!::GetPrivateProfileString(section, key, _default, buf, len, m_FileName))
				buf[0] = 0;

			return buf;
		}

		double SimpleIniFile::ReadFloat(
			const TCHAR* section,
			const TCHAR* key,
			double _default)
		{
			TCHAR value[64];

			if (ReadString(section, key, NULL, value, sizeof(value)/sizeof(value[0])))
			{
				TCHAR *endptr = NULL;
				return _tcstod(value, &endptr);
			}
			else
				return _default;
		}

	}
}